package com.gate.way.demo.config;

import limiter.DefaultRateLimiter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.support.ConfigurationService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

/**
 * @author wangzhilong
 * @date 2021/3/22
 */
@Configuration
public class RateLimitConfig {

    private final Logger log = LoggerFactory.getLogger(getClass());

    /**
     * 限流规则：有参数user的请求都需要进行限流
     * 使用这种方式限流，请求路径中必须携带user参数。
     * @return
     */
    @Bean
    KeyResolver userKeyResolver() {
       log.info("限流器启动");
        return exchange -> {
            MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
            String user = queryParams.getFirst("user");
            if (ObjectUtils.isEmpty(user)) {
                return Mono.just("");
            } else {
                return Mono.just(user);
            }
        };
    }

    /**
     * 创建基于guava的本地限流组件
     * 引入 Redis之后 默认引入了 RedisRateLimiter 限流器
     * @param configurationService
     * @return
     */
    @Bean
    @Primary
    DefaultRateLimiter defaultRateLimiter(ConfigurationService configurationService){
        return new DefaultRateLimiter(configurationService);
    }

}
